from django.db import models
from django.conf import settings


class Artwork(models.Model):
    """作品模型"""
    
    # 作品类型选项
    TYPE_CHOICES = [
        ('painting', '绘画'),
        ('music', '音乐'),
        ('writing', '写作'),
    ]
    
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, 
        on_delete=models.CASCADE, 
        related_name='artworks',
        db_comment='创作者ID'
    )
    type = models.CharField(
        max_length=20, 
        choices=TYPE_CHOICES,
        db_comment='作品类型'
    )
    title = models.CharField(
        max_length=200,
        db_comment='作品标题'
    )
    description = models.TextField(
        blank=True, 
        null=True,
        db_comment='作品描述'
    )
    content = models.TextField(
        db_comment='作品内容（存储URL或文本）'
    )
    style = models.CharField(
        max_length=50, 
        blank=True, 
        null=True,
        db_comment='风格标签'
    )
    parameters = models.JSONField(
        blank=True, 
        null=True,
        db_comment='生成参数'
    )
    view_count = models.IntegerField(
        default=0,
        db_comment='浏览量'
    )
    like_count = models.IntegerField(
        default=0,
        db_comment='点赞量'
    )
    comment_count = models.IntegerField(
        default=0,
        db_comment='评论数'
    )
    is_public = models.BooleanField(
        default=True,
        db_comment='是否公开'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_comment='创作时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        db_comment='更新时间'
    )
    
    class Meta:
        db_table = 'creation_artworks'
        db_table_comment = 'AI艺术作品表'
        verbose_name = '作品'
        verbose_name_plural = '作品管理'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'type']),
            models.Index(fields=['created_at']),
            models.Index(fields=['is_public']),
        ]
    
    def __str__(self):
        return f"{self.title} ({self.get_type_display()})"
    
    def increment_view_count(self):
        """增加浏览量"""
        self.view_count += 1
        self.save(update_fields=['view_count'])
    
    def increment_like_count(self):
        """增加点赞量"""
        self.like_count += 1
        self.save(update_fields=['like_count'])
    
    def decrement_like_count(self):
        """减少点赞量"""
        if self.like_count > 0:
            self.like_count -= 1
            self.save(update_fields=['like_count'])
    
    def increment_comment_count(self):
        """增加评论数"""
        self.comment_count += 1
        self.save(update_fields=['comment_count'])
